package com;

import Untils.JDBCUntils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Test7 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;
        try {
            //1.获取连接
            conn = JDBCUntils.getconnection();
            //开启事务

            //2.定义sql
            //2.1 张三 - 500
            String sql1 = "update worker set banlance = banlance - ? where id = ?";
            //2.2 李四 + 500
            String sql2 = "update worker set banlance = banlance + ? where id = ?";
            //3.获取执行sql对象
            ps1 = conn.prepareStatement(sql1);
            ps2 = conn.prepareStatement(sql2);
            //4. 设置参数
            ps1.setDouble(1,500);
            ps1.setInt(2,1);

            ps2.setDouble(1,1000);
            ps2.setInt(2,2);
            //5.执行sql
//            conn.commit();
            ps1.executeUpdate();
            ps2.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ps1 != null) {
                try {
                    ps1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps2 != null) {
                try {
                    ps2.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
